package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SimUserPurse;
import org.dromara.system.domain.bo.SimUserPurseBo;
import org.dromara.system.domain.bo.SimUserPurseRecordsBo;
import org.dromara.system.domain.vo.QueryUserPurseVo;
import org.dromara.system.domain.vo.SimUserPurseVo;
import org.dromara.system.enums.SysUserProfitRecordsEnum;
import org.dromara.system.mapper.SimUserPurseMapper;
import org.dromara.system.service.ISimUserPurseRecordsService;
import org.dromara.system.service.ISimUserPurseService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户钱包Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimUserPurseServiceImpl extends ServiceImpl<SimUserPurseMapper, SimUserPurse>
    implements ISimUserPurseService {


    /**
     * 查询用户钱包
     *
     * @param id 主键
     * @return 用户钱包
     */
    @Override
    public SimUserPurseVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户钱包列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户钱包分页列表
     */
    @Override
    public TableDataInfo<SimUserPurseVo> queryPageList(SimUserPurseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SimUserPurse> lqw = buildQueryWrapper(bo);
        Page<SimUserPurseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户钱包列表
     *
     * @param bo 查询条件
     * @return 用户钱包列表
     */
    @Override
    public List<SimUserPurseVo> queryList(SimUserPurseBo bo) {
        LambdaQueryWrapper<SimUserPurse> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimUserPurse> buildQueryWrapper(SimUserPurseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SimUserPurse> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimUserPurse::getId);
        lqw.eq(bo.getUserId() != null, SimUserPurse::getUserId, bo.getUserId());
        lqw.eq(bo.getProfit() != null, SimUserPurse::getProfit, bo.getProfit());
        return lqw;
    }

    /**
     * 新增用户钱包
     *
     * @param bo 用户钱包
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimUserPurseBo bo) {
        SimUserPurse add = MapstructUtils.convert(bo, SimUserPurse.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户钱包
     *
     * @param bo 用户钱包
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimUserPurseBo bo) {
        SimUserPurse update = MapstructUtils.convert(bo, SimUserPurse.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimUserPurse entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户钱包信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public QueryUserPurseVo queryUserPurse(SimUserPurseBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimUserPurse simUserPurse = lambdaQuery().eq(SimUserPurse::getUserId, bo.getUserId()).one();
        if (ObjectUtil.isNull(simUserPurse)) {
            return QueryUserPurseVo.builder().profit(BigDecimal.ZERO).cumulativeIncome(BigDecimal.ZERO).build();
        }
        BigDecimal profit = simUserPurse.getProfit();
        //查询累计收入佣金
        ArrayList<Integer> typeList = CollUtil.newArrayList(SysUserProfitRecordsEnum.RENEW.getCode());
        SimUserPurseRecordsBo build = SimUserPurseRecordsBo.builder().userId(bo.getUserId()).typeList(typeList).build();
        ISimUserPurseRecordsService iSimUserPurseRecordsService = SpringUtil.getBean(ISimUserPurseRecordsService.class);
        BigDecimal queryTotalAmountByType = iSimUserPurseRecordsService.queryTotalAmountByType(build);
        return QueryUserPurseVo.builder().profit(profit).cumulativeIncome(queryTotalAmountByType).build();
    }

    @Override
    public TableDataInfo<SimUserPurseVo> userAccounting(SimUserPurseBo bo, PageQuery pageQuery) {
        IPage<SimUserPurseVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimUserPurseVo> list = baseMapper.userAccounting(page, bo);
        return TableDataInfo.build(list);
    }
}
